<?php
  defined('_JEXEC') or die();
  jimport('joomla.application.component.model');
  require_once('base.php');
  
  class GameStatModelGameStat extends BaseModel
  {     
    var $_name = "gamestat";
    var $_table = "#__pbny_game_stats";
    
    function get_list_summary($id = null){  # change this
      
      $t_schedule        = '#__pbny_schedules';
      $t_team            = '#__pbny_teams';
      $t_game_end_status = '#__pbny_game_end_status';
      
      $sql = 'SELECT gs.*,s.schedule,t1.name as first_team,
              t2.name as second_team,ges.name as game_end_status '.
                   'FROM '. $this->_table .' gs '.
           "LEFT JOIN $t_schedule s ON s.id=gs.schedule_id ".
           "LEFT JOIN $t_team t1 ON t1.id=s.first_team_id ".
           "LEFT JOIN $t_team t2 ON t2.id=s.second_team_id ".
           "LEFT JOIN $t_game_end_status ges ON gs.game_end_status_id=ges.id";
      
      $where = null;
      if($id)
        $where = ' WHERE id = ' . $id;
      
      $this->_sql = $sql;
          
      return $this->getListData();
    }
    
    function get_by($schedule_id = null, $game_end_status_id = null, $published = null){
    
      $where = " WHERE true";
      if(isset($schedule_id))
        $where .= " AND schedule_id = $schedule_id ";
        
      if(isset($game_end_status_id))
        $where .= " AND game_end_status_id = $game_end_status_id";
        
      if(isset($published))
        $where .= " AND published = $published";
        
      $sql = 'SELECT * '.
             'FROM '.$this->_table.
           $where;
           
      return $this->_get($sql);
    }
	
	# this method should be revised and changed, because its ugly
    function get_season_standings($season_id){
      
      $sql = 'SELECT gs.*, s.first_team_id as first_team_id, 
	                 s.second_team_id as second_team_id '.
           "FROM $this->_table gs ".
           'LEFT JOIN #__pbny_schedules s ON s.id = gs.schedule_id '.
           'LEFT JOIN #__pbny_division_conferences dc on dc.conference_id = s.conference_id '.
           'LEFT JOIN #__pbny_season_divisions sd on sd.division_id = dc.division_id '.
           'LEFT JOIN #__pbny_seasons ss on ss.id = sd.season_id '.
           'WHERE s.schedule BETWEEN ss.start_date AND ss.end_date '.
           " AND sd.season_id=$season_id ";

      $stats  =  $this->_get($sql);
	  if(!$stats)
        return $stats;
      #print_r($stats[0]);die('x');
      $result      = array();
      $l3          = array();
      $gb_team     = array();
      $data        = array();
      $palwd       = array();
        
      foreach($stats as $stat){
      
        if(!isset($data[$stat->schedule_id]))
          $data[$stat->schedule_id] = array();
        
        $data[$stat->schedule_id][$stat->first_team_id] = $stat;
		$data[$stat->schedule_id][$stat->second_team_id] = $stat;
        
		#l3
        if(!isset($l3[$stat->first_team_id]))
          $l3[$stat->first_team_id] = array();
		  
		if(!isset($l3[$stat->second_team_id]))
          $l3[$stat->second_team_id] = array();
        
        #gb		
        if(!isset($gb_team[$stat->first_team_id]))
          $gb_team[$stat->first_team_id] = 0;
		  
		if(!isset($gb_team[$stat->second_team_id]))
          $gb_team[$stat->second_team_id] = 0;
        
		#result
        if(!isset($result[$stat->first_team_id]))
          $result[$stat->first_team_id] = array('wins' => 0, 'loss' => 0, 'gb' => 0,
		                                  'pmade' => 0, 'palwd'=> 0, 'l3' => '',
										  'streak' => 0, 'gp' => 0, 'diff' => 0);
										
		if(!isset($result[$stat->second_team_id]))
          $result[$stat->second_team_id] = array('wins' => 0, 'loss' => 0, 'gb' => 0,
		                                  'pmade' => 0, 'palwd'=> 0, 'l3' => '',
										  'streak' => 0, 'gp' => 0, 'diff' => 0);
        
		$result[$stat->first_team_id]['gp']  += 1; #gp
		$result[$stat->second_team_id]['gp'] += 1;
		
		$result[$stat->first_team_id]['pmade']  += $stat->first_team_final_score; #pmade
		$result[$stat->second_team_id]['pmade'] += $stat->second_team_final_score;
        
		$palwd = array(); #palwd
		if(!isset($palwd[$stat->first_team_id]))
		  $palwd[$stat->first_team_id] = 0;
		$palwd[$stat->first_team_id] += $stat->first_team_final_score;
		
		if(!isset($palwd[$stat->second_team_id]))
		  $palwd[$stat->second_team_id] = 0;
		$palwd[$stat->second_team_id] += $stat->second_team_final_score;
        
		if($stat->first_team_final_score!=$stat->second_team_final_score){
		
		  if($stat->first_team_final_score > $stat->second_team_final_score){
		    $result[$stat->first_team_id]['wins'] += 1; #w
			$result[$stat->second_team_id]['loss'] += 1; #l
			
            if($result[$stat->first_team_id]['streak'] <= 0)  #streak
              $result[$stat->first_team_id]['streak'] -= 1;
            elseif($result[$stat->first_team_id]['streak'] > 0)
              $result[$stat->first_team_id]['streak'] = -1;
			  
			array_push($l3[$stat->first_team_id], 1); #l3
			array_push($l3[$stat->second_team_id], 0);
			$gb_team[$stat->first_team_id] += 1; #gb
		  }
		  else{
		    $result[$stat->first_team_id]['loss'] += 1; #w
		    $result[$stat->second_team_id]['wins'] += 1; #l
			
			if($result[$stat->second_team_id]['streak'] <= 0)  #streak
              $result[$stat->second_team_id]['streak'] -= 1;
            elseif($result[$stat->second_team_id]['streak'] > 0)
              $result[$stat->second_team_id]['streak'] = -1;
			  
			array_push($l3[$stat->second_team_id], 1); #l3
			array_push($l3[$stat->first_team_id], 0);
			$gb_team[$stat->second_team_id] += 1; #gb
		  }
		}
        		
        #points allowed
		foreach(array_keys($palwd) as $tid)
          foreach($palwd as $id => $score)
            if($id != $tid)
              $result[$tid]['palwd'] += $score;
        
      }
      
      #format L3
      foreach($l3 as $team_id => $l){
      
        $str_l3 = array('w'=>0, 'l'=>0);
      
        for($i=2; $i>=0; $i--){
          if(!isset($l3[$team_id][$i]))
            continue;
          if($l3[$team_id][$i] > 0)
            $str_l3['w'] += 1;
          elseif(($l3[$team_id][$i] == 0) && isset($l3[$team_id][$i]))
            $str_l3['l'] += 1;
        }
        $result[$team_id]['l3'] = $str_l3['w'].'W '.$str_l3['l'].'L';
        
      }
      
      #gb
      arsort($gb_team);
      $base = reset($gb_team);
      foreach($gb_team as $key => $value)
        $gb_team[$key] = abs($value - $base);
      
      #format other results
      foreach($result as $team_id => $r){
        if($r['loss'] == 0)
          $r['pct'] = 100;
        else
          $r['pct'] = number_format($r['wins']/$r['loss'], 2);
        
        $r['diff']    = $r['pmade'] - $r['palwd'];
        
        if($r['streak'] < 0) #streak again //format
          $r['streak'] = abs($r['streak']).'L';
        elseif($r['streak'] > 0)
          $r['streak'] = $r['streak'].'W';
        
        $r['gb'] = $gb_team[$team_id];
        $result[$team_id] = $r;
      }
      return $result;
    
    }
  }
?>